package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class GetTPOwner
 */
//@WebServlet(description = "取得指定角色的名單", urlPatterns = { "/GetTPOwner" })
public class GetTPOwner extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetTPOwner() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/* 變數宣告 */
		Widgets wid = new Widgets();
		String returnResult = "";
		String er = request.getParameter("er");
		System.out.println("er是："+er);
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "SELECT t1.userID,t1.nickName FROM tms_personnel t1, tms_roleusermapping t2 WHERE t1.userID = t2.userID AND t2.roleID=?";
		
		if ("ALL".equalsIgnoreCase(er)|| er== null|| "".equalsIgnoreCase(er)){
			strSQL = "SELECT userID,nickName FROM tms_personnel";
		} else {
			strSQL = "SELECT t1.userID,t1.nickName FROM tms_personnel t1, tms_roleusermapping t2 WHERE t1.userID = t2.userID AND t2.roleID=?";
		}
		
		ArrayList<User> users = new ArrayList<User>();
		
		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			if (!"ALL".equalsIgnoreCase(er) &&  er!= null && !"".equalsIgnoreCase(er)){
				ps.setInt(1,Integer.parseInt(er));
			} 
			rs = ps.executeQuery();
			while (rs.next()) {
				User user = new User();
				user.setNickName(rs.getString("nickName"));
				user.setUserID(rs.getString("userID"));
				users.add(user);
			} 
			returnResult = new Gson().toJson(users);
		} catch (Exception e) {
			returnResult = "{\"errorMsg\":\""+wid.keepErrorMes(conn, ps, e,"", true)+"\"}";
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				returnResult = e.toString();
			}
		}

		/* 設定要回傳的格式 */
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(returnResult);
	}

}